<?php

namespace App\Http\Controllers\Api\Wechat;

use App\Models\Agency;
use App\Models\User;
//use App\Model\VerifyCode;
//use App\Rules\VerifyCodeRule;
use Illuminate\Auth\Events\Registered;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;

/**
 * 用户注册
 * Class RegisterController
 * @package App\Http\Controllers\Api
 */
class RegisterController extends BaseController
{
    /*
    |--------------------------------------------------------------------------
    | Register Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles the registration of new users as well as their
    | validation and creation. By default this controller uses a trait to
    | provide this functionality without requiring any additional code.
    |
    */

    use RegistersUsers;

    public $loginAfterSignUp = true;

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {

        $this->middleware('guest:api');
    }

    /**
     * Handle a registration request for the application.
     * 注册成功直接登陆，
     *
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function register(Request $request)
    {
        $this->validator($request->all())->validate();
        $data = $request->all();
        $agency = Agency::whereHas('devices', function ($query) use ($data) {
            $query->where('code', $data['device_code']);
        })->first();

        if (empty($agency)) {
            return $this->json([], config('apicode.deviceFail.msg'), config('apicode.deviceFail.code'));
        }
        Log::error($agency);
        $data['agency_id'] = $agency->id;
        $data['type_id'] = $agency->type_id;

        event(new Registered($user = $this->create($data)));

        if (!$user) {
            return $this->json([], config('apicode.registerfail.msg'), config('apicode.registerfail.code'));
        }
        Log::error("register success");
        if ($this->loginAfterSignUp) {
            //注册之后登陆，返回token数据
            $token = $this->guard()->login($user);

            return $this->json([
                'token' => $token
            ]);
        }
        //注册之后登陆，返回token数据
        return $this->json([
            'test' => 'test'
        ]);
    }

    /**
     * 发送验证码
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function code(Request $request)
    {
        $this->validate($request, [
            'email' => 'required|string|email|max:255|unique:users',
        ]);

        if (VerifyCode::send($request->input('email'))) {
            return $this->json([], '验证码已发送');
        }

        return $this->json([], config('apicode.verifyCodeSendFail.msg'), config('apicode.verifyCodeSendFail.code'));
    }

    /**
     * Get a validator for an incoming registration request.
     *
     * @param array $data
     * @return \Illuminate\Contracts\Validation\Validator
     */
    protected function validator(array $data)
    {
        return Validator::make($data, [
            'name' => 'required|string|max:255|unique:users',
            'password' => 'required|string|min:6|confirmed', //password_confirmation
            'device_code' => 'required|string|exists:devices,code',
            'phone' => 'required|string|unique:users',
            //'code' => ['required', new VerifyCodeRule()]
        ], [], [
            'device_code' => '设备硬件编号'
            //'code' => '验证码'
        ]);
    }

    /**
     * Create a new user instance after a valid registration.
     *
     * @param array $data
     * @return \App\Models\User
     */
    protected function create(array $data)
    {

        return User::create([
            'name' => $data['name'],
            'password' => bcrypt($data['password']),
            'status' => 1,
            'agency_id' => $data['agency_id'], //学校
            'type_id' => $data['type_id'], //学校
            'phone' => $data['phone'],
            'register_time' => time()
        ]);
    }

    /**
     * Get the guard to be used during registration.
     *
     * @return \Tymon\JWTAuth\JWTGuard
     */
    protected function guard()
    {
        return Auth::guard('api');
    }

    /**
     * Where to redirect users after registration.
     *
     * @return string
     */
    protected function redirectTo()
    {
        Log::error("redirectTo");
        //return route('api.index');
        //注册之后登陆，返回token数据
        return $this->json([
            'test' => 'test'
        ]);
    }
}
